import React, { Component } from 'react';
import PropTypes from 'prop-types'
import './index.css'

class Item extends Component {
    static propTypes = {
        item: PropTypes.object.isRequired,
        changeChecked: PropTypes.func.isRequired,
        handleDelete: PropTypes.func.isRequired
    }

    state = { mouse: false };

    handleMouse = (flag) => {
        return () => {
            this.setState({
                mouse: flag
            })
        }
    }

    handleChecked = (id) => {
        return (event) => {
            this.props.changeChecked(id, event.target.checked);
        }
    }

    handleDelete = (id) => {
        // window必须, 为真删除
        if (window.confirm('确定删除吗?'))
            this.props.handleDelete(id);
    }
    
    render() {
        const { item } = this.props;
        const { mouse } = this.state;
        return (
            <li style={{ backgroundColor: mouse ? '#ddd' : '' }} onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)}>
                <input type="checkbox" checked={item.done} onChange={this.handleChecked(item.id)}/>
                <span>{item.name}</span>
                {/* 这个箭头函数调用回调的方式, 不需要在回调函数中再返回一个函数 */}
                <button onClick={() => this.handleDelete(item.id)} className="btn btn-danger" style={{display: mouse ? 'block' : 'none'}}>删除</button>
            </li>
        );
    }
}

export default Item;